﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using KUMC.Neurology.SomatoTopo;
using Excel = Microsoft.Office.Interop.Excel;

namespace KUMC.Neurology.SomatoTopo
{
    public partial class FormMain : Form
    {
        /*
         * Member
         * */
        private Study m_Study = null;
        private SubjectTable m_SubjectTable = null;

        /*
         * Constructor
         * */
        public FormMain()
        {
            InitializeComponent();
        }

        /*
         * Menu
         * */
        private void newStudyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.NewStudy();
        }
        private void openStudyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.OpenStudy();
        }
        private void closeStudyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.CloseStudy();
        }
        private void saveStudyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SaveStudy();
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void exportToExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Export2Excel();
        }
        private void subjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormSubject form = new FormSubject(this.m_Study);

            if (form.ShowDialog() == DialogResult.OK)
            {
                if (m_SubjectTable != null && m_Study != null)
                {
                    m_SubjectTable.UpdateFromStudy(m_Study);
                    dataGridView.DataSource = m_SubjectTable;
                    DisplayStudyInformation();
                }
            }
        }
        private void analysisToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            FormAnalysis form = new FormAnalysis
                (m_Study.GetSubjects(), m_Study.Template, m_Study.SubjectOption, m_Study.DistributionOption, m_Study);

            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
            }
        }

        /*
         * Event
         * */
        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl.SelectedIndex)
            {
                    // Information tab
                case 0:
                    
                    break;

                    // data tab
                case 1:
                    if (m_SubjectTable != null && m_Study != null)
                    {
                        m_SubjectTable.UpdateFromStudy(m_Study);
                        dataGridView.DataSource = m_SubjectTable;
                    }
                    break;

                    // template tab
                case 2:
                    if (this.m_Study != null)
                    {
                    }
                    break;

                default:
                    break;
            }
        }
        private void pbTemplate_Paint(object sender, PaintEventArgs e)
        {
            if (this.m_Study == null)
            {
                e.Graphics.Clear(Color.White);
            }
            else
            {
                e.Graphics.DrawImage(this.m_Study.Template.Bitmap, 0, 0);
            }
        }
        private void AppMainForm_Resize(object sender, EventArgs e)
        {
            this.Layout2Form();
        }
        private void AppMainForm_Load(object sender, EventArgs e)
        {
            this.Layout2Form();
            DisplayStudyInformation();
        }

        /*
         * Function
         * */
        private void NewStudy()
        {
            FormNewStudy    form            = new FormNewStudy();
            DirectoryInfo   di              = new DirectoryInfo(Properties.Resources.STUDY_PATH);

            string      studyTitle          = null;
            string[]    subjectOption       = null;
            string[]    distributionOption  = null;
            Layer       template            = null;

            if (form.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (this.m_Study != null) { CloseStudy(); }
                    if (!di.Exists)         { di.Create();  }

                    studyTitle          = form.StudyTitle;
                    subjectOption       = form.SubjectOption.Split(',');
                    distributionOption  = form.DistributionOption.Split(',');
                    template            = new Layer(form.TemplateFile);
                    this.m_Study          = new Study(studyTitle, subjectOption, distributionOption, template);
                    this.m_SubjectTable   = new SubjectTable();

                    DisplayStudyInformation();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        private void OpenStudy()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (m_Study != null)  { CloseStudy(); }   
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    this.m_Study = (Study)Utility.BinaryDeserialize(ofd.FileName);
                    this.m_SubjectTable = new SubjectTable();

                    DisplayStudyInformation();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error : " + ex.Message);
                }
            }
        }
        private void CloseStudy()
        {
            if (m_Study != null)
            {
                this.m_Study          = null;
                this.m_SubjectTable   = null;

                DisplayStudyInformation();
            }
        }
        private void SaveStudy()
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        Utility.BinarySerialize(sfd.FileName, m_Study);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error : " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }
        
        private void Export2Excel()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = Properties.Resources.EXCEL_EXT;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    this.m_SubjectTable.Export2Excel(sfd.FileName);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        private void Layout2Form()
        {
            pnLayout.Size = ClientRectangle.Size;
            tabControl.Size = pnLayout.ClientRectangle.Size;
            
            tabData.Size = tabControl.ClientSize;
            tabInformation.Size = tabControl.ClientSize;
            tabTemplate.Size = tabControl.ClientSize;

            // information tab
            dataGridView.Size = tabData.ClientSize;
            dataGridView.Location = tabData.ClientRectangle.Location;
            pbTemplate.Size = tabTemplate.ClientSize;
            pbTemplate.Location = tabTemplate.ClientRectangle.Location;
        }
        private void DisplayStudyInformation()
        {
            if (m_Study == null)
            {
                LB_STUDYTITLE.Text = "No current study";
                TB_MAPOPT.Text = "";
                TB_SUBN.Text = "";
                TB_SUBOPT.Text = "";
            }
            else
            {
                string mapopt = "";
                string subopt = "";
                foreach(string s in m_Study.DistributionOption)
                {
                    mapopt += s + " ";
                }
                foreach(string s in m_Study.SubjectOption)
                {
                    subopt += s + " ";
                }

                LB_STUDYTITLE.Text = m_Study.Title;
                TB_MAPOPT.Text = mapopt;
                TB_SUBOPT.Text = subopt;
                TB_SUBN.Text = m_Study.GetSubjectCount().ToString();
            }
        }

        /*
         * Data Input from Excel Sheet
         * */
        private void modifyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.OpenStudy();

            /*
            string subopt = "이름,성별,나이,초재진,약복용,IRLS,병원,PSQI,ISI,ESS,Ferritin";
            string disopt = "강도,발생빈도,발생시각";
            */

            string subopt = "ID,pdf_no,pdf_no2,pdf_no3,Hosp_ID,P_Name,Sex,Age,Med_YN,Age_onset2,Age_on_cat,RLS_du2,IRLS2,FHX,FHX_2,Hemoglobin,Ferritin,Iron,Secondary,SecRLS,SecRLS_2,Secondary_reason,LL_T_Ant,LL_T_Post,LL_Calf,LL_Ant_Tib,LL_sole,LL_dorsum_f,UL_Arm,UL_FA,UL_Palm,UL_dorsum_h,Asymmetry,Unilateral,upper_only,genital,joints,back,neck,abdomen,chest,PN_like,Head,shoulder,Strange,Comments,Sx_cat1,Sx_cat2,Sx_cat3,Sx_cat4,Sx_cat4_2,Sx_cat4_3,Sx_cat5,Sx_cat5_2,Sx_cat6,Hosp,PSQI,ISI,ESS,PSG,PSG_2,PLMS_index,SIT_PLMW_index,DMax,MDS,Anemia2,Anemia2_2,PREG,PREG_2,Renal,Renal_2,NCS,NCS_2,NCS_result,NEX_NL,NEX_NL_2,NEX_result,C_DM,C_DM_2,C_PN,C_PN_2,C_Radiculopathy,C_Radiculopathy_2,C_periph_total,C_periph_total_2,NCS_ABN,NCS_ABN_2,C_Arthritis,C_Arthritis_2,C_brain_do,C_brain_do_2,PLM_Exist,PLM_Exist_2,data_degree,Exclude_reason,KMU_missing";
            string disopt = "유무";

            string studyTitle = this.m_Study.Title;
            string[] subjectOption = subopt.Split(',');
            string[] distributionOption = disopt.Split(',');
            Layer template = this.m_Study.Template;

            Study new_study = new Study(studyTitle, subjectOption, distributionOption, template);


            ////////////
            // Excel
            ////////////
            string fileName = @"C:\Analysis2.xlsx";
            string sheetName = "Analysis_2";

            Excel.Workbook workbook = null;
            Excel.Worksheet worksheet = null;
            Excel.Application application = null;

            object missing = System.Reflection.Missing.Value;

            application = new Excel.Application();
            application.Visible = false;

            workbook = application.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                                                            Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                                                            Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            worksheet = (Excel.Worksheet)workbook.Sheets[sheetName];

            int n_row = 152;
            int n_col = subopt.Split(',').Count();

            for(int r = 2; r <= n_row; r++)
            {
                string[] newopt = new string[n_col];
                int[] dist = m_Study.GetSubject(r-2).Distribution;

                for (int c = 1; c <= n_col; c++)
                {
                    Excel.Range value = worksheet.Cells[r, c];
                    if(value.Value != null)
                        newopt[c-1] = Convert.ToString(value.Value);
                }
                new_study.AddSubject(newopt, dist);
            }

            workbook.Close();
          
            string aa = "C://NewStudy";
            string savefile = Path.Combine(aa);

            Utility.BinarySerialize(savefile, new_study);

        }
    }
}
